<template>
    <van-nav-bar
      title="用户注册"
      left-text="返回"
      left-arrow
      @click-left="$router.back()"
    />
  
    <van-field v-model="tel" type="tel" label="请输入手机号" />
  
    <van-field
      v-model="sms"
      center
      clearable
      label="短信验证码"
      placeholder="请输入短信验证码"
    >
      <template #button>
        <van-button
          :disabled="tel.length !== 11"
          size="small"
          type="danger"
          @click="getSmsCode"
          >发送验证码</van-button
        >
      </template>
    </van-field>
  
    <van-field
      v-model="password"
      type="password"
      label="密码"
      placeholder="请输入密码"
    />
  
    <van-button @click="submit" :disabled="!flage" round type="danger"
      >确定</van-button
    >
  </template>
  
  <script setup lang="ts">
  import { ref, computed } from "vue";
  import { showDialog } from "vant";
  import { useRouter } from "vue-router";
  import type { Ref } from "vue";
  import { msgCode, userRegister } from "@/api/api";
  import { showConfirmDialog } from "vant";
  import { showFailToast } from "vant";

  
  interface IApiCode {
    code: string;
    data: number;
    message: string;
  }
  
  const tel = ref("");
  const router = useRouter();
  const sms: Ref<string | number> = ref("");
  const password: Ref<string> = ref("");
  const flage = computed(() => {
    return tel.value.length === 11 && sms.value && password.value;
  });
  
  const getSmsCode = () => {
    showConfirmDialog({
      title: "提示",
      message: `将向手机号：${tel.value}发送短信验证码`,
    })
      .then(async () => {
        const res = (await msgCode({
          tel: tel.value as string,
        })) as unknown as IApiCode;
        if (res.code === "200") {
          sms.value = res.data;
        }
      })
      .catch(() => {
        console.log("我取消了");
      });
  };
  
  const submit = async () => {
    const params = {
      tel: tel.value,
      password: password.value,
    };
    const res = (await userRegister(params)) as unknown as IApiCode;
    if (res.code === "200") {
      showConfirmDialog({
        title: "恭喜你注册成功",
        message: "注册成功，立即去登陆？",
      })
        .then(async () => {
          router.push("/login");
        })
        .catch(() => {
          console.log("我取消了");
        });
    } else {
      showFailToast("注册失败了");
    }
  };
  </script>
  
  <style lang="scss" scoped>
  .van-cell {
    margin-top: 80px;
    margin-bottom: 40px;
  }
  </style>
  